//ajax请求
(function (w) {
    var time;
    var netWork = function (data, method) {
            if (data.loading) data.loading();//显示加载中
            if (data.native == false) {//zepto请求
                $.ajax({
                    url: data.url,
                    type: data.method ? data.method : "get",
                    dataType: "json",
                    data: data.data,
                    timeout: data.prize ? 8000 : 40000,
                    success: function (d) {
                        if (data.endLoading) data.endLoading();//结束加载中
                        if (method) method(d);
                    },
                    error: function (res, e) {
                        //console.log(e+": "+JSON.stringify(res));
                        if (e == "timeout") {
                            tip.toast("网络比较差，请稍后再试");
                        }
                        //else if (e == "abort") {
                        //    tip.toast("网络有问题，请稍后再试");
                        //}
                        //else if (res.status == 200) {
                        //
                        //}
                        //else {
                        //    tip.toast("网络不给力，请稍后再试");
                        //}
                        cw.buttonAjax = true;
                        if (data.logger)data.logger(res, e);
                        if (data.error)data.error();
                    }
                });
            } else { //原生请求
                //jsonp跨域
                // var script = document.createElement('script');
                // script.type = "text/javascript";
                // script.src = data.url+"&callback="+method;
                // document.head.appendChild(script);
                // return;
                //正常请求
                try {
                    var xmlhttp;
                    if (window.XMLHttpRequest) {
                        xmlhttp = new XMLHttpRequest();
                    }
                    else {
                        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                    }
                    xmlhttp.onreadystatechange = function () {
                        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                            if (data.endLoading) data.endLoading();//结束加载中
                            if (method) method(xmlhttp.responseText);
                        }
                    }

                    if (data.method && data.method == "post") {
                        xmlhttp.open("post", data.url, data.sync ? false : true);
                        if (data.formData) {
                            xmlhttp.send(data.formData);
                        } else {
                            xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");//普通表单类型，键值对
                            xmlhttp.send(data.data);
                        }
                    } else {
                        xmlhttp.open("get", data.url, data.sync ? false : true);
                        xmlhttp.send();
                    }
                    time = setTimeout(function () {
                        if (data.prize && (xmlhttp.readyState != 4 || xmlhttp.status != 200)) {//抽奖按钮控制
                            xmlhttp.abort();
                            if (data.endLoading) data.endLoading();//结束加载中
                            noNetwork();
                            if (data.thisObj)data.thisObj.buttonControl = false;
                        }
                    }, 6000);
                    //setTimeout(function(){
                    //    if(data.prize && !xmlhttp.statusText){
                    //        if(document.getElementById("toast")){
                    //            xmlhttp.abort();
                    //            if(data.endLoading) data.endLoading();//结束加载中
                    //            document.getElementById("toast").innerText = "亲，请检查你的网络君～";//
                    //            document.getElementById("toast").className += " toasts";
                    //            clearTimeout(time);
                    //            if(data.thisObj)data.thisObj.buttonControl = false;
                    //            return false;
                    //        }
                    //    }
                    //},800);
                } catch (e) {
                    console.log(e.name + " " + e.message);
                } finally {

                }
            }
        },
    //获取参数key值
        getQueryString = function (name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
            var r = decodeURI(window.location.search).substr(1).match(reg);
            if (r != null) return unescape(r[2]);
            return "";
        },
    //无网络，自己调用
        noNetwork = function () {
            if (document.getElementById("toast")) {
                document.getElementById("toast").innerText = "亲，请求超时～";//亲，请检查你的网络君～
                document.getElementById("toast").className += " toasts";
            }
        },
    //图片加载错误处理
        imgLoadError = function (obj) {
            obj.src = cw.resUrl + "images/com/portrait_normal.jpg";//默认头像
        },
    //数字加0
        numTowDisplay = function (num) {
            if (num < 10 && num >= 0) {
                num = "0" + num;
            }
            return num;
        },
    //时间格式化
        formatTime = function (date) {
            return numTowDisplay(date.getFullYear()) + "-" + numTowDisplay(date.getMonth() + 1) + "-" + numTowDisplay(date.getDate()) + " " + numTowDisplay(date.getHours()) + ":" + numTowDisplay(date.getMinutes());
        },
    //公司时间规则
        formatTimeRule = function (date) {
            var d = new Date(date), now = new Date(),
                dStamp = d.getTime(), nowStamp = now.getTime();
            if (now.getFullYear() - d.getFullYear() > 0) {
                return numTowDisplay(d.getFullYear()) + "-" + numTowDisplay(d.getMonth() + 1) + "-" + numTowDisplay(d.getDate());
            } else if ((nowStamp - dStamp) / 1000 < 60) {
                return "刚刚";
            } else if ((nowStamp - dStamp) / 60000 < 60) {
                return Math.floor((nowStamp - dStamp) / 60000) + "分钟前";
            } else if ((nowStamp - dStamp) / 3600000 < 24) {
                return Math.floor((nowStamp - dStamp) / 3600000) + "小时前";
            } else if ((nowStamp - dStamp) / 86400000 >= 1 && (nowStamp - dStamp) / 86400000 <= 3) {
                return Math.floor((nowStamp - dStamp) / 86400000) + "天前";
            } else if ((nowStamp - dStamp) / 86400000 > 3) {
                return numTowDisplay(d.getMonth() + 1) + "月" + numTowDisplay(d.getDate()) + "日";
            }
        },
    //去掉空格
        trim = function (str) {
            return str.replace(/\s/g, "");
        };

    w.getQueryString = getQueryString;
    w.netWork = netWork;//ajax
    w.imgLoadError = imgLoadError;
    w.numTowDisplay = numTowDisplay;
    w.formatTime = formatTime;
    w.formatTimeRule = formatTimeRule;
    w.trim = trim;
    //控制器对象
    w.cw = {
        buttonAjax: true,
       /* resUrl: "http://d.img.66xiaoqu.com/app/",
        htmlUrl: "http://d.h5.66xiaoqu.com/app/",
        serverUrl: "http://t.app.66xiaoqu.com"*/

        resUrl: "http://66xiaoqu.babytreeimg.com/app/",
        htmlUrl: "http://h5.66xiaoqu.com/app/",
        serverUrl: "http://app-66xiaoqu.babytree.com"
    };

})(window);


//检测网络
window.addEventListener("offline", function () {
    //if(document.getElementById("toast")){
    //    document.getElementById("toast").innerText = "亲，请检查你的网络君～";
    //    document.getElementById("toast").className += " toasts";
    //}
    tip.toast("亲，请检查你的网络君～");
}, true);


/*var resUrl = "http://d.img.66xiaoqu.com/app/";
var htmlUrl = "http://d.h5.66xiaoqu.com/app/";
var serverUrl = "http://t.app.66xiaoqu.com";*/

var resUrl = "http://66xiaoqu.babytreeimg.com/app/";
var htmlUrl = "http://h5.66xiaoqu.com/app/";
var serverUrl = "http://app-66xiaoqu.babytree.com";

//function trim(str){  //删除左右两端的空格
//    return str.replace(/(^\s*)|(\s*$)/g, "");
//}
//function ltrim(str){  //删除左边的空格
//    return str.replace(/(^\s*)/g,"");
//}
//function rtrim(str){  //删除右边的空格
//    return str.replace(/(\s*$)/g,"");
//}


function toDownload() {
    var data = {"url": "http://66xiaoqu.babytreeimg.com/app/json/download_1023.json"},
        getData = function (res) {
            var res = eval("(" + res + ")");
            var u = navigator.userAgent, app = navigator.appVersion;
            var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //android�ն˻���uc�����
            var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios�ն�
            var ua = navigator.userAgent.toLowerCase();
            var isWx = ua.match(/MicroMessenger/i) === "micromessenger"
            var url = "#";
            var os = "";
            if (isAndroid) {
                url = res.android.default;
                os = "Android";
                $("div.device_text span").css("font-size", "16px");
                if (isWx) {
                    $('footer').show();
                    url = res.android.wx;
                    os = "Android";
                }
            }
            else if (isiOS) {
                url = res.android.default;
                os = "iOS"
                if (isWx) {
                    $('footer').show();
                    url = res.android.default;
                    os = "iOS";
                }
            }
            location.href = url;
        }
    netWork(data, getData);
}

var params = {};
var tempArray = window.location.search.split('?');
if (tempArray.length == 2) {
    var parts = tempArray[1].split('&');
    for (var i = 0; i < parts.length; i++) {
        var nv = parts[i].split('=');
        if (!nv[0]) continue;
        params[nv[0]] = nv[1] || true;
    }
}

function ft(input) {

    var d = new Date(input), now = new Date(),
        dStamp = d.getTime(), nowStamp = now.getTime();
    if (now.getFullYear() - d.getFullYear() > 0) {
        return d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();
    } else if ((nowStamp - dStamp) / 1000 < 60) {
        return "刚刚";
    } else if ((nowStamp - dStamp) / 60000 < 60) {
        return Math.floor((nowStamp - dStamp) / 60000) + "分钟前";
    } else if ((nowStamp - dStamp) / 3600000 < 24) {
        return Math.floor((nowStamp - dStamp) / 3600000) + "小时前";
    } else if ((nowStamp - dStamp) / 86400000 >= 1 && (nowStamp - dStamp) / 86400000 <= 3) {
        return Math.floor((nowStamp - dStamp) / 86400000) + "天前";
    } else if ((nowStamp - dStamp) / 86400000 > 3) {
        return (d.getMonth() + 1) + "月" + d.getDate() + "日";
    }
};

function setShareContent(key) {

    if (params.vcode != null && parseInt(params.vcode) >= 201000) {
        $.ajax({
            type: "POST",
            url: serverUrl + '/rest/v1.0/mobile/shares/getShareContentByKey/' + key,
            data: {},
            dataType: "json",
            success: function (data) {
                var title = data.data.title;
                var desc = data.data.desc;
                var image = data.data.shareImg;
                var url = encodeURIComponent(data.data.url);
                if (params.type == 'ios') {
                    document.location.href = "66xiaoqu:setShareContent##title=" + title + "&nbsp;desc=" + desc + "&nbsp;image=" + image + "&nbsp;url=" + url;
                } else {
                    webviewhandle.setShareContent(title, desc, image, url);//webviewhandle为webview注册对象
                }
            }
        });
    }
}

function setShareContentAndUrl(key,url) {

    if (params.vcode != null && parseInt(params.vcode) >= 201000) {
        $.ajax({
            type: "POST",
            url: serverUrl + '/rest/v1.0/mobile/shares/getShareContentByKey/' + key,
            data: {},
            dataType: "json",
            success: function (data) {
                var title = data.data.title;
                var desc = data.data.desc;
                var image = data.data.shareImg;
                if (params.type == 'ios') {
                    document.location.href = "66xiaoqu:setShareContent##title=" + title + "&nbsp;desc=" + desc + "&nbsp;image=" + image + "&nbsp;url=" + url;
                } else {
                    webviewhandle.setShareContent(title, desc, image, url);//webviewhandle为webview注册对象
                }
            }
        });
    }
}

//function setShareContent(key) {
//
//    if (params.vcode != null && parseInt(params.vcode) >= 201000) {
//        var xhr = new XMLHttpRequest();
//
//        xhr.open("POST", serverUrl + '/rest/v1.0/mobile/shares/getShareContentByKey/' + key, true);
//        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//        xhr.onreadystatechange = function () {
//            var XMLHttpReq = xhr;
//            if (XMLHttpReq.readyState == 4) {
//                if (XMLHttpReq.status == 200) {
//                    var text = XMLHttpReq.responseText;
//                    var data = JSON.parse(text);
//                    var title = data.data.title;
//                    var desc = data.data.desc;
//                    var image = data.data.shareImg;
//                    var url = encodeURIComponent(data.data.url);
//                    if (params.type == 'ios') {
//                        document.location.href = "66xiaoqu:setShareContent##title=" + title + "&nbsp;desc=" + desc + "&nbsp;image=" + image + "&nbsp;url=" + url;
//                    } else {
//                        webviewhandle.setShareContent(title, desc, image, url);//webviewhandle为webview注册对象
//                    }
//                }
//            }
//        };
//        xhr.send({});
//    }
//}